<?php
namespace app\api\controller;

use app\index\model\VisitorModel;
use think\Db;
use app\index\controller\Login as IndexLogin;

class Login extends Base {
	/**
	 * [登陆]
	 */
	public function doLogin() {
		$param = $this->params;
		$visitorModel = new VisitorModel();
        $visitor = $visitorModel->where('user_name',$param['user_name'])
			->whereOr('email',$param['user_name'])->find();
        if(empty($visitor)){
            return json(['code'=>0,'msg'=>'该账号不存在']);
        }
        if(md5($param['passwd'] . config('salt')) != $visitor['passwd']){
            return json(['code'=>0,'msg'=>'密码错误']);
        }
        if(1 != $visitor['status']){
            return json(['code'=>0,'msg'=>'该账号被禁用']);
        }
		$return = [
			"user_id" => $visitor['id'],
			"user_name" => $visitor['user_name'],
			"user_head" => $_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME']."/".$visitor['head']
		];
        return json(['code'=>1,'msg'=>'登录成功','data'=>$return]);
	}
	/**
	 * [注册]
	 */
	public function register() {
		$param = $this->params;
		$visitorModel = new VisitorModel();
		$validate = validate("VisitorValidate");
		$result = $validate->check($param);
		if(!$result){
			return json(['code'=>0,'msg'=>$validate->getError()]);
		}
		// 验证邮箱验证码
		if($param['email_code'] != session('check_email_code')){
			return json(['code'=>0,'msg'=>"邮箱验证码错误"]);
		}
		$visitorModel::startTrans();
		try {
			$data = $param;
			$data['passwd'] = md5($param['passwd'] . config('salt'));
			$data['used_passwd'] = $data['passwd'];
			$data['head'] = "/static/admin/images/user.png";
			$visitor_id = $visitorModel::insertGetId($data);
			$visitorModel::where('id',$visitor_id)->update(['nick_name' => '用户'.$visitor_id]);
			$return = [
				"user_id" => $visitor_id,
				"user_name" => $data['user_name'],
				"user_head" => $_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME']."/".$data['head']
			];
			$visitorModel::commit();
			session("check_email_code",null);
			return json(['code'=>1,'msg'=>"注册成功","data"=>$return]);
		} catch (\Exception $e) {
			$visitorModel::rollback();
			return json(['code'=>0,'msg'=>"注册失败：".$e->getMessage(),'data'=>""]);
		}
	}
	/**
	 * [获取邮箱验证码]
	 */
	public function getEmailCode() {
		$param = $this->params;
		$visitorModel = new VisitorModel();
		$isExist = $visitorModel::where('email',$param['email'])->count();
		if($isExist != 0){
			return json(['code'=>0,'msg'=>'该邮箱已被注册','data'=>'']);
		}
		$info = DB::name('api_cfg')->where('cate_id',3)->select();
		$config = [];
		foreach($info as $v){
			$config[$v['remark']] = $v['val'];
		}
		$eCode = rand(100000,999999);
		session("check_email_code",$eCode);
		$ct = "您的邮箱验证码为【".$eCode."】，请尽快完成操作。此邮件请勿回复！";
		$indexLoginCtrl = new IndexLogin();
		$res = $indexLoginCtrl->sendMail($param['email'],'您在Finalove网站申请注册的验证码',$ct,$config);
		if($res){
			return json(['code'=>1,'msg'=>'邮件发送成功，请尽快登陆邮箱，获取验证码，完成操作']);
		}else{
			return json(['code'=>0,'msg'=>'邮件发送失败，请稍后再试']);
		}
	}
}
